What is tsafe?
The tsafe package provides utility functions for TypeScript that help ensure type safety and improve type inference. It includes functions for exhaustive type checks, type assertions, and more.
What are tsafe's main functionalities?
exhaustiveSwitch
The exhaustiveSwitch function is used to ensure that all possible cases in a switch statement are handled. If a case is not handled, it throws an error, helping developers catch missing cases at compile time.
function exhaustiveSwitch(value: never): never { throw new Error(`Unhandled case: ${value}`); }
assert
The assert function is used to assert that a condition is true. If the condition is false, it throws an error. This is useful for runtime checks that also inform TypeScript's type system.
function assert(condition: any, msg?: string): asserts condition { if (!condition) { throw new Error(msg); } }
Other packages similar to tsafe
ts-essentials
The ts-essentials package provides a set of essential utilities for TypeScript, including advanced types and type guards. It offers more comprehensive utilities compared to tsafe, focusing on enhancing TypeScript's type system capabilities.
type-fest
Type-fest is a collection of essential TypeScript types. It provides a wide range of utility types that extend TypeScript's built-in types, offering more flexibility and power. While tsafe focuses on runtime type safety, type-fest is more about enhancing type definitions.
A collection of utilities to take your TypeScript development up a notch
You can cherry-pick what you import
Documentation
Make sure two types are identical
Playground
A assertion function that typescript understands
Make sure your zod schema exactly matches a given type:
Playground
Make sure you never forget a case in a switch
Playground
Make TypeScript believe whatever you say without having to write const obj2 = obj as Bar
.
The more powerfully is to be able to tell TypeScript that obj
ist not of type Bar
:
Motivations
Powerful TypeScript features like assertion functions or user-defined type guards are only useful if paired with utility functions.
TypeScript, however, only exports type helpers (e.g. Record
, ReturnType
, etc.).
This module provides «the missing builtins» such as the assert function and other utilities that cannot be just type helpers.
Documentation website
Installation
tsafe
is both an NPM and a Deno module.
(Achieved with denoify)
Import in deno:
import { assert, type Equals, ... } from "https://deno.land/x/tsafe/mod.ts";
Install elsewhere:
$ npm install --save tsafe